import React, { Component } from 'react';
import Editor from '@/utils/Editor';
import { Icon, Radio, Select, Button, Table, Row, Col } from 'antd';
import { FormattedMessage } from 'umi-plugin-react/locale';
import styles from './index.less';
import { connect } from "dva/index";
import { message } from "antd/lib/index";
const MyIcon = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1131883_m18hmgbwet.js', // 在 iconfont.cn 上生成
});
import { knowledgeDialogSlots, knowledgeDialogActionNodeInfo } from '@/services/dialog';
import UserSession from '../../../UserSession';

@connect(({ dialogCommon, loading }) => ({
  dialogCommon,
  loading: loading.models.data,
}))
class ActionApi extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      dialogId: props.dialogId,
      nodeId: props.nodeId,
      stage: props.stage,
      stageId: "",
      slots: [],
      apiList: [],
      requestFieldList: [],
      responseFieldList: [],
      currentApi: '',
      mapping: [],
    };
  }

  componentDidMount() {
    this.getInit();
    this.loadActionApis();
    this.getDialogSlots();
  };

  getInit = async () => {
    const { dispatch } = this.props;
    const { nodeId, dialogId, stage } = this.state;
    if (UserSession.isSystemKnowledge()) {
      let res = await knowledgeDialogActionNodeInfo({ dialogId, nodeId });
      this.setState({
        stageId: res.id,
        currentApi: res.api == null ? "" : res.api.apiId,
        mapping: res.api == null ? [] : res.api.mapping,
      }, () => {
        if (res.api && res.api.apiId) {
          this.loadApiFields(this.state.currentApi);
        }
      });
    } else {
      dispatch({
        type: 'dialogCommon/getActionData',
        payload: {
          dialogId: dialogId,
          nodeId: nodeId,
          urlPrefix: UserSession.isSystemKnowledge() ? 1 : null,
        },
        callback: (res) => {
          this.setState({
            stageId: res.id,
            currentApi: res.api == null ? "" : res.api.apiId,
            mapping: res.api == null ? [] : res.api.mapping,
          }, () => {
            if (res.api && res.api.apiId) {
              this.loadApiFields(this.state.currentApi);
            }
          });
        }
      });
    }
  };

  getDialogSlots = async () => {
    const { dialogId } = this.state;
    const { dispatch } = this.props;
    if (UserSession.isSystemKnowledge()) {
      let res = await knowledgeDialogSlots({ dialogId })
      this.setState({
        slots: res == null ? [] : res,
      })
    } else {
      dispatch({
        type: 'dialogCommon/getDialogSlots',
        payload: {
          dialogId: dialogId,
          urlPrefix: UserSession.isSystemKnowledge() ? 1 : null,
        },
        callback: (res) => {
          this.setState({
            slots: res == null ? [] : res,
          })
        }
      });
    }
  };

  loadActionApis = () => {
    const { dispatch } = this.props;
    const { nodeId, dialogId, stage } = this.state;

    dispatch({
      type: 'dialogCommon/loadActionApis',
      payload: {
        page: 0,
        limit: 99999,
        urlPrefix: UserSession.isSystemKnowledge() ? 1 : null,
      },
      callback: (res) => {

        this.setState({
          apiList: res == null ? [] : res,
        });
      }
    });
  };

  loadApiFields = (apiId) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'dialogCommon/loadActionApi',
      payload: {
        apiId: apiId,
        urlPrefix: UserSession.isSystemKnowledge() ? 1 : null,
      },
      callback: (res) => {

        this.setState({
          requestFieldList: res.requestFields == null ? [] : res.requestFields,
          responseFieldList: res.requestFields == null ? [] : res.responseFields,
        })
      }
    });
  };

  changeCurrentApi = (val) => {
    this.setState({
      currentApi: val,
      mapping: [],
    })
    this.loadApiFields(val);
  };

  addField = () => {
    const { mapping } = this.state;
    mapping.push(
      {
        apiField: "",
        slotId: "",
        fieldType: "N",
      }
    )
    this.setState({
      mapping
    })
  };

  changeSelect = (val, valType, index) => {

    const { mapping } = this.state;
    mapping[index][valType] = val;
    if (valType == "fieldType") {
      mapping[index].apiField = '';
    }
    this.setState({
      mapping: mapping,
    }, () => {

    })
  };

  removeMapping = (index) => {
    const { mapping } = this.state;
    mapping.splice(index, 1);
    this.setState({
      mapping
    })
  }

  save = () => {
    const { stage, nodeId, dialogId } = this.state
    const obj = {
      id: this.state.stageId ? this.state.stageId : dialogId + '-' + nodeId,
      field: "api",
      api: {
        apiId: this.state.currentApi,
        mapping: this.state.mapping,
        setTime: new Date().getTime(),
      },
      stage
    }



    const { dispatch } = this.props;
    dispatch({
      type: 'dialogCommon/saveStage',
      payload: obj,
      callback: (res) => {

        message.info(res.msg);
        this.props.closeDrawer();
      }
    });
  };

  render() {
    const columns = [
      {
        title: '词槽',
        width: '30%',
        render: (text, item, index) => {
          return (
            <div>
              <Select
                style={{ width: '100%' }} value={item.slotId} onChange={(value) => this.changeSelect(value, "slotId", index)}>
                <Select.Option value=''>请选择</Select.Option>
                {
                  this.state.slots.map((slotItem, index) =>
                    <Select.Option value={slotItem.id} key={index}>{slotItem.name}</Select.Option>
                  )
                }
              </Select>
            </div>
          )
        }
      },
      {
        title: 'API字段',
        width: '60%',
        render: (text, item, index) => {
          return (
            <div>
              <Select
                style={{ width: '40%' }} value={item.fieldType} onChange={(value) => this.changeSelect(value, "fieldType", index)}>
                <Select.Option value='N'>请选择</Select.Option>
                <Select.Option value="request">请求字段</Select.Option>
                <Select.Option value="response">返回字段</Select.Option>
              </Select>
              -
              <Select
                style={{ width: '40%' }} value={item.apiField} onChange={(value) => this.changeSelect(value, "apiField", index)}>
                <Select.Option value="">请选择</Select.Option>
                {
                  item.fieldType == "request" ?
                    this.state.requestFieldList.map((field, index) =>
                      <Select.Option value={field.id}>{field.name}</Select.Option>
                    ) :
                    this.state.responseFieldList.map((field, index) =>
                      <Select.Option value={field.id}>{field.name}</Select.Option>
                    )
                }
              </Select>
            </div>
          )
        }
      },
      {
        title: '操作',
        width: '10%',
        render: (text, item, index) => {
          return <div className={styles.pb}>
            <div
              onClick={() => this.removeMapping(index)}
              style={{ marginLeft: 10, background: '#e8313b' }}
              className={styles.buttongl}>
              <span><Icon size="small" type='delete' style={{ marginRight: 5 }} />
              </span><span> <FormattedMessage id="app.dialog.question.delete" defaultMessage="out" /></span>
            </div>
          </div>
        }
      }
    ]
    return (
      <div>
        <div style={{ margin: '15px 0px', paddingLeft: '30px' }} tt="2">
          API接口&nbsp;&nbsp;&nbsp;&nbsp;
          <Radio.Group value={1}>
            <Radio value={1}>自定义API接口</Radio>
          </Radio.Group>
          <Select
            style={{ width: '32%' }} value={this.state.currentApi} onChange={(value) => this.changeCurrentApi(value)}>
            <Select.Option value=''>请选择接口</Select.Option>
            {
              this.state.apiList.map((item, index) =>
                <Select.Option value={item._id}>{item.name}</Select.Option>
              )
            }
          </Select>
        </div>

        <div>
          <div>
            {/*<Icon style={{transform: 'rotate(90deg)'}} type="minus"/>词槽-字段对应*/}
            <Row>
              <Col xs={24}>
                <div className={styles.title}>
                  <span>词槽-字段对应</span>
                </div>
              </Col>
            </Row>
            <Table
              columns={columns}
              dataSource={this.state.mapping}//数据
              pagination={false}
              style={{ marginLeft: '20px', marginTop: '20px' }}
            />
          </div>
          <div style={{ marginBottom: '30px' }}>
            <div style={{ marginLeft: '20px' }}>
              <span style={{ color: '#8EC0F9', cursor: "pointer" }} onClick={this.addField}>+ 添加</span>
            </div>
          </div>
        </div>

        <div
          style={{
            position: 'absolute',
            right: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
          }}
        >
          <Button onClick={this.props.closeDrawer} style={{ marginRight: 8 }}>
            取消
          </Button>
          <Button onClick={this.save} disabled={UserSession.isSystemKnowledge()} type="primary">
            确定
          </Button>
        </div>
      </div>

    )
  }
}

export default ActionApi;
